import { message } from "antd";
import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from "axios";
import { values } from "lodash";
import { HttpRequestConfig, ResultData } from "@/api/interface";
import { store } from "@/store";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import { axiosCanceler } from "@/api/helper/axiosCancel";
import { setToken } from "@/store/modules/global";
import { tryHideFullScreenLoading, showFullScreenLoading } from "@/config/serviceLoading";
import NProgress from "@/config/nprogress";

//登录失效只触发一次
let LoginStatusFlag = false;

const InitialConfig = {
	// 默认地址请求地址
	baseURL: import.meta.env.VITE_API_URL,
	// 设置超时时间（10s）
	timeout: 10000,
	// 跨域时候允许携带凭证（cookie）
	withCredentials: false
};

class RequestHttp {
	service: AxiosInstance;
	constructor(config: AxiosRequestConfig) {
		//实例化axios
		this.service = axios.create(config);

		//请求前的拦截处理，添加store中的token
		this.service.interceptors.request.use(
			(config: AxiosRequestConfig) => {
				//浏览器进度条显示
				NProgress.start();
				//如果当前请求需要显示 loading,在api服务中通过指定的第三个参数: { headers: { showLoading: true } }来控制显示loading
				if (config.headers?.showLoading) showFullScreenLoading();
				//将当前请求添加到 pending 中
				axiosCanceler.addPending(config);

				//添加token
				const token = store.getState().global.token;
				const tokenObj: any = {};
				if (token) {
					tokenObj.token = token;
				}
				return { ...config, headers: { ...config.headers, ...tokenObj } };
			},
			(error: AxiosError) => {
				return Promise.reject(error);
			}
		);

		//请求结束后返回的拦截处理
		this.service.interceptors.response.use(
			async (response: AxiosResponse) => {
				const { config, data } = response;

				//关闭浏览器进度条
				NProgress.done();
				//在请求结束后，移除本次请求(关闭loading)
				axiosCanceler.removePending(config);
				//关闭全局loading
				tryHideFullScreenLoading();

				/**
				 *处理下载文件
				 */
				if (config.responseType === "blob") {
					const code = data?.code;
					if (code) {
						const arr = [];
						if (arr.indexOf(code) > -1) {
							message.error("出错了");
						}
						return undefined;
					} else {
						return response;
					}
				}

				/**
				 * 处理登录状态
				 */
				const LoginStatusCode = [-2];
				if (LoginStatusCode.indexOf(data?.code) > -1) {
					if (!LoginStatusFlag) {
						message.error(data?.msg);
						LoginStatusFlag = true;
						// window.location.href = "/user/login";
						store.dispatch(setToken(""));
						setTimeout(() => {
							LoginStatusFlag = false;
						});
					}
					return data;
				}

				/**
				 * 如果code在不拦截对象里面并且code不为0，则弹出提示
				 */
				if (data?.code !== RESULT_CODES.SUCCESS) {
					message.error(data?.msg);
					return data;
				}
				return data;
			},
			(error: AxiosError) => {
				const { response } = error;
				console.log("=======error:", response);
				//关闭浏览器进度条
				NProgress.done();
				//关闭全局loading
				tryHideFullScreenLoading();

				// 根据响应的错误状态码，做不同的处理
				if (response) {
					const { data, status }: any = response;
					if (data && !data?.code) {
						message.error(data?.msg);
					} else {
						const errorText = response.statusText;
						message.error(errorText);
					}
				} else {
					// 请求超时单独判断，请求超时没有 response
					if (error.message.indexOf("timeout") !== -1) {
						message.error("请求超时，请稍后再试");
					}
				}
				return Promise.reject(error);
			}
		);
	}

	//get请求封装
	get(url: string, params?: object, _config: HttpRequestConfig = {}): Promise<ResultData> {
		return this.service.get(url, { params, ..._config });
	}

	//post请求封装
	post(url: string, data?: object, _config: HttpRequestConfig = {}): Promise<ResultData> {
		return this.service.post(url, data, { ..._config });
	}

	//delete请求封装
	delete(url: string, params?: object, _config: HttpRequestConfig = {}): Promise<ResultData> {
		return this.service.delete(url, { params, ..._config });
	}
}

export default new RequestHttp(InitialConfig);
